package com.chromatic.competition.service;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.chromatic.competition.inteface.UserInitializationService;
import com.chromatic.competition.model.Friend;
import com.chromatic.competition.utils.RetrofitClientUtil;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FriendsListFetchService extends ViewModel {
    private final MutableLiveData<List<Friend>> friends;
    private int currentUserId;

    /**
     * 构造函数，初始化 friends 对象
     */
    public FriendsListFetchService() {
        friends = new MutableLiveData<>();
    }

    /**
     * 获取好友列表数据的 LiveData 对象
     *
     * @return LiveData 对象，观察者可以通过它来获取好友列表数据
     */
    public LiveData<List<Friend>> getFriends() {
        return friends;
    }

    /**
     * 设置当前用户的 ID，并加载好友列表视图
     *
     * @param userId 当前用户的 ID
     */
    public void setCurrentUserId(int userId) {
        this.currentUserId = userId;
        loadFriendsListView();
    }
    /**
     * 加载好友列表视图
     */
    public void loadFriendsListView() {
        RetrofitClientUtil retrofitClientUtil = RetrofitClientUtil.getInstance();
        UserInitializationService userInitializationService = retrofitClientUtil.getApiService();

        Call<List<Friend>> call = userInitializationService.getUserFriendsListView(currentUserId);
        call.enqueue(new Callback<List<Friend>>() {
            @Override
            public void onResponse(@NonNull Call<List<Friend>> call, @NonNull Response<List<Friend>> response) {
                if (response.isSuccessful()) {
                    List<Friend> friendDTOList = response.body();
                    if (friendDTOList != null) {
                        friends.setValue(new ArrayList<>(friendDTOList));
                    }
                } else {
                    Log.e("FriendsListView", "获取好友列表失败，响应码：" + response.code());
                }
            }

            @Override
            public void onFailure(@NonNull Call<List<Friend>> call, @NonNull Throwable t) {
                Log.e("FriendsListView", "获取好友列表失败，错误：" + t.getMessage());
            }
        });
    }
}